import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {}
    }
  },
  mutations: {
    updateToken(state, payload) {
      state.token = payload
      setToken(payload)
    },
    delToken(state, payload) {
      state.token = ''
      removeToken()
    },
    getUser(state, payload) {
      state.userInfo.name = payload
    }
  },
  actions: {
    // 登录
    async storeLogin(context, payload) {
      const { token, userName } = await login(payload)
      context.commit('getUser', userName)

      context.commit('updateToken', token)
    },

    // 登出
    storeUserOut(context) {
      context.commit('delToken')
      context.commit('getUser', {})
    }
  }
}
